//
//  DescVedioCell.m
//  XiaoHongShu
//
//  Created by Jason on 2022/7/2.
//

#import "DescVideoCell.h"
#import <AVFoundation/AVFoundation.h>
#import "MainDataModel.h"
#import <YYText/YYText.h>
#import "NSAttributedString+YYText.h"
#import <UIButton+LXMImagePosition.h>
#import "NSNumber+KeepDigital.h"
#import "BNCommonProgressBar.h"
#import "UIView+Extend.h"
#import "CommentView.h"


#define BNSliderLeftRightMargin 64
#define BNSliderHeight 20

#define BNBtnWid 132
#define BNBtnHeight 42
#define BNTimderDuration 0.3
#define BNTotalProgress 10

/**
 sub desc 位置和长度
 */
@interface DescRange : NSObject

@property (nonatomic, assign) NSUInteger location;
@property (nonatomic, assign) NSUInteger length;

@end

@implementation DescRange

-(NSString *)description {
    return [NSString stringWithFormat:@"location: %ld, length: %ld", self.location, self.length];
}

@end

/**
 每一段desc的内容、是否为topic、是否为@
 */
@interface DescDetail : NSObject

@property (nonatomic, copy) NSString *desc;
@property (nonatomic, assign) Boolean isTopic;
@property (nonatomic, assign) Boolean isAt;

@end

@implementation DescDetail

-(NSString *)description {
    return [NSString stringWithFormat:@"desc:[%@], isTopic: %hhu, isAt: %hhu", self.desc, self.isTopic, self.isAt];
}

@end

@interface DescVideoCell ()<BNCommonProgressBarDelegate, UIScrollViewDelegate>
//播放器对象
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *currentPlayerItem;
@property (nonatomic, strong) id timeObserver;
//显示视频的容器
@property (nonatomic, strong) UIView *containerView;
//返回按钮
@property (nonatomic, strong) UIButton *backBtn;
//分享按钮
@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, strong) UIImageView *userImgView;
//用户名 + 昵称
@property (nonatomic, strong) UIButton *userInfoBtn;

//关注按钮
@property (nonatomic, strong) UIButton *attentionBtn;
//正文
@property (nonatomic, strong) YYLabel *textLabel;
//用来计算一行文本的高度
@property (nonatomic, assign) CGFloat titleMaxH;
//限定宽度下一行文本的个数
@property (nonatomic, assign) CGFloat textcount;

@property (nonatomic, assign) CGRect originTextLabelFrame;

//遮罩Btn
@property (nonatomic, strong) UIButton *shadeBtn;

// descText
@property (nonatomic, strong) NSMutableString *descText;
@property (nonatomic, strong) NSMutableString *subDescText;
@property (nonatomic, strong) NSMutableString *showAllDescText;
@property (nonatomic, strong) NSMutableArray<DescRange *> *rangeMarr;
@property (nonatomic, strong) NSMutableAttributedString *attributedText;
@property (nonatomic, strong) NSMutableAttributedString *showAllAttributedText;
//@property (nonatomic, strong) NSMutableString *descStr;

@property (nonatomic, strong) NSMutableArray *descRange;

//记录是否点击 nameText + descFirstText 文本
@property (nonatomic, assign) BOOL hasClickedNameAndDescFirstText;

//隐藏用户信息按钮
@property (nonatomic, strong) UIButton *isHideUserInfoBtn;

//是否点击了隐藏用户信息按钮
@property (nonatomic, assign) BOOL hasClickHideUserInfoBtn;


//显示视频创建时间地点
@property (nonatomic, strong) UIButton *createTimeBtn;

//收起按钮
@property (nonatomic, strong) UIButton *packUpBtn;

//播放进度滑块
//@property (nonatomic, strong) CustomSlider *sliderView;
@property (nonatomic, strong) BNCommonProgressBar *progressBar;

@property (nonatomic, assign) CGFloat curProgress;

//视频暂停按钮
@property (nonatomic, strong) UIButton *pauseBtn;

//是否点击了暂停播放按钮
@property (nonatomic, assign) BOOL hasClickedPuaseBtn;

//底部View
@property (nonatomic, strong) UIView *bottomView;

//底部弹幕按钮
@property (nonatomic, strong) UIButton *subtitlesBtn;

@property (nonatomic, assign) BOOL clickedSubtitleBtn;

@property (nonatomic, strong) UIButton *bottomBtn;


//点赞按钮
@property (nonatomic, strong) UIButton *likeBtn;

//收藏按钮
@property (nonatomic, strong) UIButton *collectBtn;

//评论按钮
@property (nonatomic, strong) UIButton *commentBtn;

@property (nonatomic, strong) UIView *bgView;

//评论列表上拉的页数
@property (nonatomic, assign) NSInteger pageNum;


@end

@implementation DescVideoCell

-(void)setMainModel:(MainDataModel *)mainModel {
    _mainModel = mainModel;
    //视频播放
    //[self vedioPlay];
  //  mainModel.textDescription = @"看得好快乐就是说！[自拍R][自拍R][自拍R]日常记录  孤勇者  刘畊宏直播  刘畊宏  # #正则表达式[话题]# #解析字符串格式[话题]# #零基础转码[话题]#";
    _descText = [NSMutableString stringWithFormat:@"%@ %@", mainModel.name, mainModel.textDescription];
    _subDescText = [NSMutableString stringWithString:[_descText stringByReplacingOccurrencesOfString:@"\n" withString:@" "]];
//    _descText = [NSMutableString stringWithString:@"140秒记录装修全过程 回想8个多月的装修记录并没有心酸 #### #我的安格鲁貂[话题]# #大头[话题]# #睡觉自由[话题]#"];
//    _subDescText = [NSMutableString stringWithString:@"140秒记录装修全过程 回想8个多月的装修记录并没有心酸，只有满满的成就感，只有满满的成就感 #### #我的安格鲁貂[话题]# #大头[话题]# #睡觉自由[话题]#"];
//    NSLog(@"sliderViewY2 = %f", CGRectGetHeight(self.containerView.frame) - CGRectGetHeight(self.sliderView.frame));
//    NSLog(@"sliderViewY3 = %f", self.containerView.frame.size.height - self.sliderView.frame.size.height);
//    NSLog(@"原始containerViewH = %f", self.containerView.frame.size.height);
//    NSLog(@"原始sliderViewH = %f", self.sliderView.frame.size.height);
    // TODO 需要动态高度
    self.textLabel.frame = CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width - 80, 0);
    
    _attributedText = [self generateTextAttribute:_subDescText];
    
    _showAllAttributedText = [self generateTextAttribute:_descText];
    
    CGFloat subDescHeight = [self returnTextHeightWithStr:_subDescText withFont:[UIFont systemFontOfSize:14.0] WithWidth:[UIScreen mainScreen].bounds.size.width - 80 WithLineSpacing:0];
    CGFloat descHeight = [self returnTextHeightWithStr:_descText withFont:[UIFont systemFontOfSize:14.0] WithWidth:[UIScreen mainScreen].bounds.size.width - 80 WithLineSpacing:0];
    NSLog(@"subDescHeight: %f, descHeight: %f", subDescHeight, descHeight);
    
    NSLog(@"_subDescText = %@", _attributedText.string);
    NSLog(@"textLength = %ld, _textcount = %f", _attributedText.string.length, _textcount);
    CGRect textLabelFrame = self.textLabel.frame;
    //动态设置 textLabel 的高度
    if (_attributedText.string.length < _textcount) {
        textLabelFrame.size.height = _titleMaxH * 1;
        textLabelFrame.origin.y = CGRectGetHeight(self.containerView.frame) - 20 - _titleMaxH * 1;
    } else {
        textLabelFrame.size.height = _titleMaxH * 2;
        textLabelFrame.origin.y = CGRectGetHeight(self.containerView.frame) - 20 - _titleMaxH * 2;
    }
    _originTextLabelFrame = textLabelFrame;
    self.textLabel.frame = _originTextLabelFrame;
    NSLog(@"textLabelFrame = %@", NSStringFromCGRect(self.textLabel.frame));
    
    self.textLabel.attributedText = _attributedText;
    
    //用户名
    [_userInfoBtn setTitle:mainModel.userName forState:UIControlStateNormal];
    //用户头像
    [_userImgView sd_setImageWithURL:[NSURL URLWithString:mainModel.userImage]];
    
    [_createTimeBtn setTitle:mainModel.lastModifiedAt forState:UIControlStateNormal];
    
    //关注按钮
    if (!mainModel.hadAttention) {
        [self.attentionBtn setTitle:@"关注" forState:UIControlStateNormal];
        self.attentionBtn.backgroundColor = kRedColor;
    } else {
        [self.attentionBtn setTitle:@"已关注" forState:UIControlStateNormal];
        _attentionBtn.backgroundColor = kClearColor;
    }
    
    
    //喜欢数量
    [self.likeBtn setTitle: [self countWithModelCount:mainModel.likeCount btnTag:self.likeBtn.tag] forState:UIControlStateNormal];
    if (_mainModel.inLike == true) {
        [_likeBtn setImage:kImageName(@"dianzan_sel") forState:UIControlStateNormal];
    } else {
        [_likeBtn setImage:kImageName(@"dianzan") forState:UIControlStateNormal];
    }
    
    
    //收藏数量
    [self.collectBtn setTitle: [self countWithModelCount:mainModel.collectCount btnTag:self.collectBtn.tag] forState:UIControlStateNormal];
    if ([mainModel.collectBtnImageName isEqualToString:@"shoucang_sel"]) {
        [_collectBtn setImage:kImageName(@"shoucang_sel") forState:UIControlStateNormal];
    } else {
        [_collectBtn setImage:kImageName(@"shoucang") forState:UIControlStateNormal];
    }
    
    //评论数量
    [self.commentBtn setTitle:[self countWithModelCount:mainModel.commentCount btnTag:self.commentBtn.tag] forState:UIControlStateNormal];
}

//获取不同情况的数量
- (NSString *)countWithModelCount:(NSUInteger)mainModelCount btnTag:(NSInteger)btnTag{
    //获取没有超过一万的数量
    if (mainModelCount > 10000) {
        return [NSString stringWithFormat:@"%@ 万", [NSNumber keepOneDigitWithCount:mainModelCount / 10000.0]];
    } else if (mainModelCount > 0){
        return [NSString stringWithFormat:@"%ld", mainModelCount];
    } else {
        if (btnTag == 0) {
            return @"喜欢";
        } else if (btnTag == 1) {
            return @"收藏";
        } else {
            return @"评论";
        }
    }
}

//纯代码创建控件，需要重写
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //创建控件
        self.hasClickedNameAndDescFirstText = NO;
        [self setUpUI];
        
    }
    return self;
}

-(UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc]init];
        _containerView.backgroundColor = kOrangeColor;
        //打开视图的交互模式
        _containerView.userInteractionEnabled = YES;  //打开交互
        //创建点按手势
        UITapGestureRecognizer *tapGesR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTapAction:)];
        [_containerView addGestureRecognizer:tapGesR];
    }
    return _containerView;
}

//返回按钮
-(UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [[UIButton alloc]init];
        [_backBtn setImage:kImageName(@"back") forState:UIControlStateNormal];
        _backBtn.backgroundColor = kGreenColor;
        [_backBtn addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

//返回按钮的点击事件
- (void)backBtnClicked {
    NSLog(@"点击了返回按钮");
    if ([self.delegate respondsToSelector:@selector(descVideoCell:backBtnClicked:player:)]) {
        [self.delegate descVideoCell:self backBtnClicked:self.backBtn player:self.player];
    }
}

//分享按钮
-(UIButton *)shareBtn {
    if (!_shareBtn) {
        _shareBtn = [[UIButton alloc]init];
        [_shareBtn setImage:kImageName(@"share") forState:UIControlStateNormal];
        _shareBtn.backgroundColor = kGreenColor;
        [_shareBtn addTarget:self action:@selector(shareBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareBtn;
}

//分享按钮的点击事件
- (void)shareBtnClicked {
    NSLog(@"点击了分享按钮");
}

//视频进度滑块
//-(UISlider *)sliderView {
//    if (!_sliderView) {
//        _sliderView = [[CustomSlider alloc]init];
//        _sliderView.frame = CGRectMake(10, kSPScreenHeight - [UIDevice vg_tabBarFullHeight] - 3, kSPScreenWidth - 20, 30);
//        _sliderView.backgroundColor = kGreenColor;
//        [_sliderView addTarget:self action:@selector(sliderViewChanged:) forControlEvents:UIControlEventValueChanged];
//    }
//    return _sliderView;
//}

- (BNCommonProgressBar *)progressBar {
    if (!_progressBar) {
        // Frame: BNCommonProgressBar 的frame
        // defaultColor: 滑块条的颜色
        // barHeight: 滑块条的高度
        // dotHeight：如果滑块有图片，滑块按钮的高度
        // inProgressColor: 滑块的颜色
        // dragColor: 已经滑过的滑块条的颜色
        // cornerRadius: leftView 和 rightView 的圆角半径
        // progressBarIconImage: 滑块图片
        // enablePanProgressIcon:  是否可以拖拽滑块
        _progressBar = [[BNCommonProgressBar alloc]initWithFrame:CGRectMake(10, kSPScreenHeight - [UIDevice vg_tabBarFullHeight] - 5, kSPScreenWidth - 20, 10) barHeight:1 dotHeight:15 defaultColor: kLightGrayColor inProgressColor:kWhiteColor dragColor:kWhiteColor cornerRadius:0.5 progressBarIconImage:nil enablePanProgressIcon:YES];
        _progressBar.delegate = self;
        _progressBar.backgroundColor = [UIColor redColor];
    }
    return _progressBar;
}

//去掉圆形的大按钮
- (void)removeBigRoundButton {
    // 生成透明图片
     CGSize s = CGSizeMake(1, 1);
         UIGraphicsBeginImageContextWithOptions(s, 0, [UIScreen mainScreen].scale);
         UIRectFill(CGRectMake(0, 0, 1, 1));
         UIImage *img=UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
    [self.backBtn setImage:img forState:UIControlStateNormal];
    // 添加图片，大按钮就去掉了，这个img置为空是去不掉的
       //  [_sliderView setThumbImage:img forState:UIControlStateNormal];
}


#pragma mark - BNCommonProgressBarDelegate
-(void)progressBarCurPlayPrecent:(CGFloat)precent dragState:(BNCommonGestureState)dragState {
    if (dragState == BNCommonGestureStateMove) {
        NSTimeInterval playTime = self.progressBar.value * CMTimeGetSeconds(self.player.currentItem.duration);
        CMTime seekTime = CMTimeMake(playTime, 1);
        [self.player seekToTime:seekTime completionHandler:^(BOOL finished) {
            if (finished) {
//                // YES，进度条高度4；NO，进度条高度为2
//                self.progressBar.showLargeBar = YES;
//                // YES，展示圆点；NO，隐藏圆点
//                self.progressBar.showAnchorPoint = YES;
//                [UIView animateWithDuration:4 animations:^{
//
//                } completion:^(BOOL finished) {
//                    if (finished) {
//                        // YES，进度条高度4；NO，进度条高度为2
//                        self.progressBar.showLargeBar = NO;
//                        // YES，展示圆点；NO，隐藏圆点
//                        self.progressBar.showAnchorPoint = NO;
//                    }
//                }];
                if (self.hasClickedPuaseBtn) {
                    self.pauseBtn.hidden = self.hasClickedPuaseBtn;
                    self.hasClickedPuaseBtn = !self.hasClickedPuaseBtn;
                }
                [self.player play];
            }
        }];
    }
}

//UISlider的响应方法:拖动滑块，改变播放进度
//- (void)sliderViewChanged:(UISlider *)slider {
//    if(self.player.status == AVPlayerStatusReadyToPlay){
//        NSTimeInterval playTime = self.sliderView.value * CMTimeGetSeconds(self.player.currentItem.duration);
//        CMTime seekTime = CMTimeMake(playTime, 1);
//        [self.player seekToTime:seekTime completionHandler:^(BOOL finished) {
//            if (finished) { //滑动完成后，继续播放视频
//                if (self.hasClickedPuaseBtn) {
//                    self.pauseBtn.hidden = self.hasClickedPuaseBtn;
//                } else {
//                    self.pauseBtn.hidden = !self.hasClickedPuaseBtn;
//                }
//                [self.player play];
//                self.hasClickedPuaseBtn = !self.hasClickedPuaseBtn;
//              //  [self removeBigRoundButton];
//            }
//        }];
//    }
//}

//发布的文本
-(YYLabel *)textLabel {
    if (!_textLabel) {
        _textLabel = [YYLabel new];
        _textLabel.backgroundColor = [UIColor lightGrayColor];
        _textLabel.numberOfLines = 0;
        //是否展示异步数据
        _textLabel.displaysAsynchronously = YES;
        [self createSeemoreLabel];
    }
    return _textLabel;
}

//用户名 + 头像
- (UIButton *)userInfoBtn {
    if (!_userInfoBtn) {
        _userImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        _userImgView.backgroundColor = kYellowColor;
        _userInfoBtn = [[UIButton alloc]init];
        _userInfoBtn.backgroundColor = kRedColor;
        [_userInfoBtn setImagePosition:LXMImagePositionLeft spacing:40];
        _userInfoBtn.titleLabel.font = kBoldFont(14);
        //设置按钮文字颜色
        [_userInfoBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        //设置按钮整体居左
        _userInfoBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _userImgView.layer.cornerRadius = 15;
        _userImgView.layer.masksToBounds = YES;
        [_userInfoBtn addSubview:_userImgView];
        [_userInfoBtn addTarget:self action:@selector(userInfoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _userInfoBtn;
}

- (void)userInfoBtnClick {
    NSLog(@"点击用户头像");
}

//关注按钮
-(UIButton *)attentionBtn {
    if (!_attentionBtn) {
        _attentionBtn = [[UIButton alloc]init];
        _attentionBtn.titleLabel.font = kFont(13);
        _attentionBtn.layer.cornerRadius = 10;
        _attentionBtn.layer.masksToBounds = YES;
        [_attentionBtn addTarget:self action:@selector(attentionBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _attentionBtn;
}

//点击关注按钮
- (void)attentionBtnCLick:(UIButton *)sender {
    NSLog(@"点击关注按钮");
    //对mainModel中的hadAttention属性取反
    self.mainModel.hadAttention = !self.mainModel.hadAttention;
    //获取mainModel
    MainDataModel *cusMainModel = self.mainModel;
    if (self.mainModel.hadAttention) {
        [sender setTitle:@"已关注" forState:UIControlStateNormal];
        sender.backgroundColor = kClearColor;
        sender.layer.borderColor = kWhiteColor.CGColor;
        sender.layer.borderWidth = 1;
        cusMainModel.hadAttention = YES;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认不再关注" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
            [sender setTitle:@"关注" forState:UIControlStateNormal];
            sender.backgroundColor = kRedColor;
            cusMainModel.hadAttention = NO;
            sender.layer.borderWidth = 0;
        }]];
        //单视图跳转显示弹框
        //由于此时是在 cell 里面，self 调用不了 presentViewController：方法
        
    } else {
        [sender setTitle:@"关注" forState:UIControlStateNormal];
        sender.backgroundColor = kRedColor;
        cusMainModel.hadAttention = NO;
        sender.layer.borderWidth = 0;
    }
    self.mainModel = cusMainModel;
}

//隐藏用户信息按钮
-(UIButton *)isHideUserInfoBtn {
    if (!_isHideUserInfoBtn) {
        self.hasClickHideUserInfoBtn = NO;
        _isHideUserInfoBtn = [[UIButton alloc]init];
        _isHideUserInfoBtn.backgroundColor = kBlackColor;
        _isHideUserInfoBtn.alpha = 0.5;
        [_isHideUserInfoBtn setImage:kImageName(@"zhankai") forState:UIControlStateNormal];
        _isHideUserInfoBtn.layer.cornerRadius = 12;
        _isHideUserInfoBtn.layer.masksToBounds = YES;
        [_isHideUserInfoBtn addTarget:self action:@selector(isHideUserInfoBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _isHideUserInfoBtn;
}

//隐藏用户信息按钮的点击事件
- (void)isHideUserInfoBtnClicked:(UIButton *)sender {
    self.hasClickHideUserInfoBtn = !self.hasClickHideUserInfoBtn;
    NSLog(@"隐藏用户信息按钮的点击事件");
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:5 animations:^{
        self.hasClickHideUserInfoBtn ? [weakSelf.isHideUserInfoBtn setImage:kImageName(@"shouqi") forState:UIControlStateNormal] : [weakSelf.isHideUserInfoBtn setImage:kImageName(@"zhankai") forState:UIControlStateNormal];
        weakSelf.userInfoBtn.hidden = weakSelf.hasClickHideUserInfoBtn;
        weakSelf.attentionBtn.hidden = weakSelf.hasClickHideUserInfoBtn;
        weakSelf.textLabel.hidden = weakSelf.hasClickHideUserInfoBtn;
    }];
}

//显示视频创建时间地点
-(UIButton *)createTimeBtn {
    if (!_createTimeBtn) {
        _createTimeBtn = [[UIButton alloc]init];
        _createTimeBtn.backgroundColor = kClearColor;
        //[_createTimeBtn setTitle:@"收起" forState:UIControlStateNormal];
        [_createTimeBtn setTitleColor:kLightGrayColor forState:UIControlStateNormal];
        _createTimeBtn.titleLabel.font = kFont(10);
        //设置标签在按钮中的对齐方式
        _createTimeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_createTimeBtn addTarget:self action:@selector(packUpBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _createTimeBtn.hidden = YES;
    }
    return _createTimeBtn;
}

//收起按钮
-(UIButton *)packUpBtn {
    if (!_packUpBtn) {
        _packUpBtn = [[UIButton alloc]init];
        _packUpBtn.backgroundColor = kClearColor;
        [_packUpBtn setTitle:@"收起" forState:UIControlStateNormal];
        [_packUpBtn setTitleColor:kLightGrayColor forState:UIControlStateNormal];
        _packUpBtn.titleLabel.font = kFont(14);
        //设置标签在按钮中的对齐方式
        _packUpBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_packUpBtn addTarget:self action:@selector(packUpBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _packUpBtn.hidden = YES;
    }
    return _packUpBtn;
}

//收起按钮点击事件
- (void)packUpBtnClick {
    NSLog(@"收起按钮点击事件");
    //[self noTopicTextTapAction:self.hasClickedNameAndDescFirstText];
    [self noTopicTextTapAction];
}

//遮罩按钮
-(UIButton *)shadeBtn {
    if (!_shadeBtn) {
        _shadeBtn = [[UIButton alloc]init];
        _shadeBtn.backgroundColor = kBlackColor;
        _shadeBtn.hidden = YES;
        _shadeBtn.alpha = 0.6;
        [_shadeBtn addTarget:self action:@selector(shadeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shadeBtn;
}

//点击遮罩按钮
- (void)shadeBtnClick {
    NSLog(@"点击遮罩按钮");
    [self noTopicTextTapAction];
}

//视频暂停按钮
-(UIButton *)pauseBtn {
    if (!_pauseBtn) {
        _pauseBtn = [[UIButton alloc]init];
        _pauseBtn.backgroundColor = kClearColor;
        [_pauseBtn setImage:kImageName(@"bofang") forState:UIControlStateNormal];
        _pauseBtn.hidden = NO;
        self.hasClickedPuaseBtn = YES;
        [_pauseBtn addTarget:self action:@selector(pauseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pauseBtn;
}

//视频暂停按钮点击事件
- (void)pauseBtnClick:(UIButton *)sender {
    NSLog(@"点击视频暂停按钮");
    sender.hidden = self.hasClickedPuaseBtn;
    if (!sender.hidden) {
        //暂停视频的播放
        [self.player pause];
    } else {
        //播放视频
        [self.player play];
//        [self.progressBar resumeAnimation];
//        self.progressBar.showLargeBar = NO;
//        //隐藏滑块
//        self.progressBar.showAnchorPoint = NO;
        [UIView animateWithDuration:2 animations:^{
            
        }];
    }
    self.hasClickedPuaseBtn = !self.hasClickedPuaseBtn;
}

//底部View
-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.backgroundColor = kYellowColor;
        //创建点按手势
        UITapGestureRecognizer *tapGesR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTapAction:)];
        [_bottomView addGestureRecognizer:tapGesR];
    }
    return _bottomView;
}

//底部弹幕按钮
-(UIButton *)subtitlesBtn {
    if (!_subtitlesBtn) {
        _subtitlesBtn = [[UIButton alloc]init];
        _subtitlesBtn.backgroundColor = kBlackColor;
        _subtitlesBtn.layer.cornerRadius = 15;
        _subtitlesBtn.layer.masksToBounds = YES;
        _subtitlesBtn.alpha = 0.6;
        [_subtitlesBtn setImage:kImageName(@"bofangqi-danmukai") forState:UIControlStateNormal];
        [_subtitlesBtn setTitle:[NSString stringWithFormat:@"     l  发弹幕"] forState:UIControlStateNormal];
        _subtitlesBtn.titleLabel.font = kFont(12);
        [_subtitlesBtn setTitleColor:kLightGrayColor forState:UIControlStateNormal];
        self.clickedSubtitleBtn = YES;
        //设置按钮整体居左
        _subtitlesBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_subtitlesBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
        [_subtitlesBtn addTarget:self action:@selector(subTitleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _subtitlesBtn;
}

- (void)subTitleBtnClick:(UIButton *)sender {
    NSLog(@"点击开始发弹幕");
    if (self.clickedSubtitleBtn) {
        [self.subtitlesBtn setImage:kImageName(@"bofangqi-danmuguan") forState:UIControlStateNormal];
    } else {
        [_subtitlesBtn setImage:kImageName(@"bofangqi-danmukai") forState:UIControlStateNormal];
    }
    self.clickedSubtitleBtn = !self.clickedSubtitleBtn;
}


- (void)createBottomButton {
    CGFloat btnWidth = ((kSPScreenWidth - 20) - kSPScreenWidth * 0.32) / 3;
    CGFloat btnHeight = 30;
    CGFloat btnY = kSPScreenHeight - [UIDevice vg_tabBarFullHeight] + 5 + 10;
    CGFloat subtitleBtnMaxX = kSPScreenWidth * 0.32 + 10;
    for (int i = 0; i < 3; i++) {
        UIButton *btn = [[UIButton alloc]init];
        CGFloat btnX = subtitleBtnMaxX + i * btnWidth;
        btn.frame = CGRectMake(btnX, btnY, btnWidth, btnHeight);
        btn.backgroundColor = kPurpleColor;
        btn.titleLabel.font = kFont(10);
        btn.tag = i;
        if (i == 0) {
            self.likeBtn = btn;
            self.likeBtn.tag = i;
        } else if (i == 1) {
            self.collectBtn = btn;
            self.collectBtn.tag = i;
        } else {
            self.commentBtn = btn;
            self.commentBtn.tag = i;
            [self.commentBtn setImage:kImageName(@"pinglun") forState:UIControlStateNormal];
        }
        [btn setImagePosition:LXMImagePositionLeft spacing:5];
        [btn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:btn];
    }
}

- (void)buttonClick:(UIButton *)sender {
    //获取 mainMode 数据
    MainDataModel *cusMainModel = self.mainModel;
    if (sender.tag == 0) {
        NSLog(@"点击喜欢按钮");
        self.mainModel.inLike = !self.mainModel.inLike;
        NSUInteger cusLikeCount = self.mainModel.likeCount;
        if (self.mainModel.inLike == true) {
                cusMainModel.likeBtnImageName = @"dianzan_sel";
                cusLikeCount += 1;
                cusMainModel.inLike = true;
            } else {
                cusMainModel.likeBtnImageName = @"dianzan";
                cusLikeCount -= 1;
                cusMainModel.inLike = false;
            }
            cusMainModel.likeCount = cusLikeCount;
            [sender setTitle:[self countWithModelCount:cusLikeCount btnTag:sender.tag] forState:UIControlStateNormal];
            [sender setImage:kImageName(cusMainModel.likeBtnImageName) forState:UIControlStateNormal];
            
    } else if (sender.tag == 1) {
        NSLog(@"点击收藏按钮");
        self.mainModel.inCollect = !self.mainModel.inCollect;
        NSUInteger cusCollectCount = self.mainModel.collectCount;
        if (self.mainModel.inCollect) {
            cusMainModel.collectBtnImageName = @"shoucang_sel";
            cusCollectCount += 1;
            cusMainModel.inCollect = true;
            } else {
                cusMainModel.collectBtnImageName = @"shoucang";
                cusCollectCount -= 1;
                cusMainModel.inCollect = false;
            }
        cusMainModel.collectCount = cusCollectCount;
        [sender setTitle:[self countWithModelCount:cusCollectCount btnTag:sender.tag] forState:UIControlStateNormal];
        [sender setImage:kImageName(cusMainModel.collectBtnImageName) forState:UIControlStateNormal];
    } else {
        NSLog(@"点击评论按钮");
        
        //评论界面的背景View
        if (!_bgView) {
            _bgView = [[UIView alloc]init];
            _bgView.frame = [UIScreen mainScreen].bounds;
            _bgView.backgroundColor = [UIColor clearColor];
            [[JZGTool getCurrentVC].view addSubview:_bgView];
            // [self.contentView addSubview:_bgView];

            UIButton *topClearBtn = [[UIButton alloc]init];
            topClearBtn.frame = CGRectMake(0, 0, kSPScreenWidth, kSPScreenHeight * 1 / 4);
            topClearBtn.backgroundColor = [UIColor clearColor];
            [_bgView addSubview:topClearBtn];
            [topClearBtn addTarget:self action:@selector(topClearBtnClick) forControlEvents:UIControlEventTouchUpInside];

            UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(topClearBtn.frame), kSPScreenWidth, kSPScreenHeight - CGRectGetHeight(topClearBtn.frame))];
            scrollView.backgroundColor = kClearColor;
            scrollView.delegate = self;
            scrollView.layer.cornerRadius = 10;
            scrollView.layer.masksToBounds = YES;
            scrollView.contentSize = CGSizeMake(kSPScreenWidth, kSPScreenHeight);
            [_bgView addSubview:scrollView];
            
            //遮罩View
            UIView *maskView = [[UIView alloc]initWithFrame:_bgView.bounds];
            maskView.backgroundColor = kBlackColor;
            maskView.alpha = 0.2;
            maskView.userInteractionEnabled = YES;
            maskView.hidden = YES;

            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickToHide)];
            [maskView addGestureRecognizer:tap];
            
            CommentView *commentView = [[CommentView alloc]initWithFrame:scrollView.bounds];
            if (@available (iOS 13.0, *)) {
                commentView.backgroundColor = [UIColor systemGroupedBackgroundColor];
            } else {
                commentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            }
            commentView.layer.cornerRadius = 10;
            commentView.layer.masksToBounds = YES;
            commentView.commentCountLabel.text = [NSString stringWithFormat:@"共 %ld 条评论", self.mainModel.commentCount];
            commentView.noteId = self.mainModel.ID;
            self.pageNum = 1;
            [commentView loadRequestWithRefreshType:MJRefreshTypePullDown currentPage:self.pageNum];
            //上拉加载
            MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                self.pageNum++;
                [commentView loadRequestWithRefreshType:MJRefreshTypePullUp currentPage:self.pageNum];
                NSLog(@"commentView - 上拉加载");
            }];
            [footer setTitle:@"- THE END -" forState:MJRefreshStateNoMoreData];
            
            commentView.tableView.mj_footer = footer;
            
            [_bgView addSubview: maskView];
            //传值
            commentView.coverView = maskView;
                        
            [scrollView addSubview:commentView];
        } else {
            //恢复到变换前的状态
            self.bgView.transform = CGAffineTransformIdentity;
        }
    }
    _mainModel = cusMainModel;
}

- (void)clickToHide {
    NSLog(@"clickToHide");
    //把键盘叫回去，让view结束编辑
    [self.bgView endEditing:YES];
    NSLog(@"clickToHide - %@",self.superview.superview);
}


- (void)topClearBtnClick {
    NSLog(@"topClearBtnClick");
    //平移动画
    self.bgView.transform = CGAffineTransformMakeTranslation(0, kSPScreenHeight);
   // CGAffineTransform transform = CGAffineTransformIdentity;
   // self.bgView.transform = CGAffineTransformTranslate(transform, 0, kSPScreenHeight);
     //   self.bgView.hidden = YES;
}

//不让scrollView可以上划
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"--- scrollViewDidScroll ---");
    if (scrollView.contentOffset.y > 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
}

//判断scrollView滑到一定的高度将 bgView 向下平移
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    NSLog(@"--scrollViewWillEndDragging");
    if (scrollView.contentOffset.y < -20) {
        [self topClearBtnClick];
    }
}


#pragma mark - createSeemoreLabel
- (void)createSeemoreLabel {
    NSString *moreString = @" 展开全文";
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" ... %@", moreString]];
    NSRange expandRange = [text.string rangeOfString:moreString];
    
    [text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:expandRange];
    [text addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:NSMakeRange(0, expandRange.location)];
    
    //添加点击事件
    //初始化点击事件的类YYTextHighlight
    YYTextHighlight *hi = [YYTextHighlight new];
    [text yy_setTextHighlight:hi range:[text.string rangeOfString:moreString]];
    //创建 展开全文label 添加在 textLabel 的后面
    YYLabel *seeMore = [YYLabel new];
    __weak typeof(self) weakSelf = self;
    
    hi.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        //点击展开
        [weakSelf noTopicTextTapAction];
        NSLog(@"点击了text = %@, containerView = %@, range = %@ ",text, containerView, NSStringFromRange(range));
    };
    
    text.yy_font = [UIFont systemFontOfSize:14.0];
    seeMore.backgroundColor = [UIColor yellowColor];
    seeMore.attributedText = text;
    [seeMore sizeToFit];
    
    //truncation 是强制在末尾加上一个 label
    NSAttributedString *truncationToken = [NSAttributedString yy_attachmentStringWithContent:seeMore contentMode:UIViewContentModeCenter attachmentSize:seeMore.frame.size alignToFont:text.yy_font alignment:YYTextVerticalAlignmentTop];
    
    self.textLabel.truncationToken = truncationToken;
}

#pragma mark - 设置展开和收回状态下的frame
- (void)setTextLabelFrame:(BOOL)isExpand {
    if (isExpand) {
        //设置展开后的富文本
        self.textLabel.attributedText = _showAllAttributedText;
        YYTextContainer *titleContarer = [YYTextContainer new];
        //限制宽度
        titleContarer.size = CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, CGFLOAT_MAX);
        YYTextLayout *titleLayout = [YYTextLayout layoutWithContainer:titleContarer text:_showAllAttributedText];
        CGFloat titleLabelHeight = titleLayout.textBoundingSize.height;
        NSLog(@"---titleLabelWidth = %f", titleLayout.textBoundingSize.width);
        self.textLabel.frame = CGRectMake(10, self.containerView.frame.size.height - self.progressBar.frame.size.height - 20 - titleLabelHeight - 20, [UIScreen mainScreen].bounds.size.width - 20, titleLabelHeight);
    }
    else {
        //设置收回后的富文本
        self.textLabel.attributedText = _attributedText;
//        self.textLabel.frame = CGRectMake(10, self.containerView.frame.size.height - self.sliderView.frame.size.height - 20 - _titleMaxH * 2, [UIScreen mainScreen].bounds.size.width - 80, _titleMaxH * 2);
        self.textLabel.frame = _originTextLabelFrame;
//        NSLog(@"textLabelFrame2 = %@", NSStringFromCGRect(self.textLabel.frame));
//        NSLog(@"sliderViewY4 = %f", self.containerView.frame.size.height - self.sliderView.frame.size.height);
//        NSLog(@"展开containerViewH = %f", self.containerView.frame.size.height);
//        NSLog(@"展开sliderViewH = %f", self.sliderView.frame.size.height);
        
    }
}

//点按手势实现
- (void)doTapAction:(UITapGestureRecognizer *)sender {
    NSLog(@"点按手势实现");
    [self pauseBtnClick:self.pauseBtn];
    NSLog(@"sender = %@, view = %@", sender, sender.view);
}

#pragma mark - setUpUI
- (void)setUpUI {
    //获取底部标签栏的高度
    CGFloat statusBarH = [UIDevice vg_tabBarFullHeight];
    NSLog(@"statusBarH = %f", statusBarH);
    self.containerView.frame = CGRectMake(0, 0, kSPScreenWidth, kSPScreenHeight - statusBarH);
    [self.contentView addSubview:self.containerView];
    NSLog(@"---containerViewFrame = %@",NSStringFromCGRect(self.containerView.frame));
    
    //暂停按钮
    [self.contentView addSubview:self.pauseBtn];
    [self.pauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.mas_equalTo(self.containerView);
    }];
    
    //遮罩按钮
    [self.contentView addSubview:self.shadeBtn];
    [_shadeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.mas_equalTo(self.containerView);
    }];
    
    [self.contentView addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@25);
        make.left.equalTo(self.containerView).mas_offset(15);
        make.top.equalTo(self.containerView).mas_offset(65);
    }];
    
    [self.contentView addSubview:self.shareBtn];
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backBtn);
        make.width.height.equalTo(self.backBtn);
        make.right.equalTo(self.containerView).mas_offset(-15);
    }];
    
    [self.contentView addSubview:self.progressBar];
    //[self.contentView addSubview:self.sliderView];
//    [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(self.containerView);
//        make.left.mas_equalTo(self.containerView).mas_offset(10);
//       // make.height.mas_equalTo(2);
//        make.right.mas_equalTo(self.containerView).mas_offset(-10);
//    }];
//    NSLog(@"---slideViewMinY = %f", CGRectGetMinY(self.sliderView.frame));
//    NSLog(@"---sliderViewMaxY = %f",CGRectGetMaxY(self.sliderView.frame));
//    NSLog(@"sliderViewY1 = %f", CGRectGetHeight(self.containerView.frame) - CGRectGetHeight(self.sliderView.frame));
//    NSLog(@"---sliderViewH = %f", self.sliderView.frame.size.height);
    
    _titleMaxH = 0;
    //这是一行用来计算高度的文本
    NSString *str = @"这";
    CGSize strSize = [self calculateSizeWithString:str textSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 80, MAXFLOAT) textFont:kFont(14)];
    
    _titleMaxH = strSize.height * 1;
    NSLog(@"titleMaxH = %f",_titleMaxH);
    
    CGFloat titleWidth = strSize.width;
    NSLog(@"titleMaxW = %f", strSize.width);
    //一行中文本的个数
    _textcount = ([UIScreen mainScreen].bounds.size.width - 80) / titleWidth;
    NSLog(@"textCount = %f， width = %f", _textcount, [UIScreen mainScreen].bounds.size.width);
    
    [self.contentView addSubview:self.textLabel];
    
    [self.contentView addSubview:self.userInfoBtn];
    [self.userInfoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.textLabel.mas_top).mas_offset(-20);
        make.left.mas_equalTo(self.containerView).mas_offset(10);
        make.height.mas_equalTo(30);
    }];
    
    [self.contentView addSubview:self.attentionBtn];
    [self.attentionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.userInfoBtn).mas_offset(-5);
        make.left.mas_equalTo(self.userInfoBtn.mas_right).mas_offset(10);
        make.right.mas_lessThanOrEqualTo(self.containerView.mas_right).mas_offset(-20);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(20);
    }];
    
    [self.contentView addSubview:self.isHideUserInfoBtn];
    [self.isHideUserInfoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(24);
        make.right.mas_equalTo(self.containerView).mas_offset(-10);
        make.bottom.mas_equalTo(self.textLabel);
    }];
    
    [self.contentView addSubview:self.createTimeBtn];
    [self.createTimeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.progressBar);
        make.right.mas_equalTo(self.progressBar).multipliedBy(0.5);
        make.bottom.mas_equalTo(self.progressBar.mas_top).mas_offset(-10);
        make.height.mas_equalTo(20);
    }];
    
    [self.contentView addSubview:self.packUpBtn];
    [self.packUpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.height.mas_equalTo(self.createTimeBtn);
        make.left.mas_equalTo(self.createTimeBtn.mas_right);
        make.right.mas_equalTo(self.progressBar);
    }];
    
    [self.contentView addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.contentView);
        make.height.mas_equalTo(statusBarH - 5);
        make.top.mas_equalTo(self.containerView.mas_bottom).mas_offset(5);
    }];
    
    [self.contentView addSubview:self.subtitlesBtn];
    [self.subtitlesBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.bottomView).mas_offset(10);
        make.width.mas_equalTo(self.bottomView).multipliedBy(0.32);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(self.bottomView).mas_offset(10);
    }];
    
    [self createBottomButton];
}

- (NSMutableAttributedString *) generateTextAttribute:(NSMutableString *)descText {
    // 获取topic range
    NSMutableArray<DescRange *> *topicRangeMarr = [self regexOfTopicTextWithDescText: descText];
    NSLog(@"----> descText = %@", descText);
    NSLog(@"----> topicRangeMarr = %@", topicRangeMarr);
    
    // 将desc分成每一段, 获取desc range
    NSMutableArray *descRange = [self splitDesc:descText topicRanges:topicRangeMarr];
    NSLog(@"----> descRange : %@", descRange);
    
    NSDictionary *descDict = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor whiteColor]};
    NSDictionary *topicDict = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor greenColor]};
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:descText attributes:descDict];
    
    //topic 点击事件
    YYTextHighlight *topicHighlight = [YYTextHighlight new];
    for (DescRange *descRange in topicRangeMarr) {
        NSRange range = NSMakeRange(descRange.location, descRange.length);
        NSString *showTopic = [attributedText.string substringWithRange: range];
        NSLog(@"处理 [%@] topic", showTopic);
        
        [attributedText addAttributes:topicDict range:NSMakeRange(descRange.location, descRange.length)];

        //topicText 的点击事件
        [attributedText yy_setTextHighlight: topicHighlight range:NSMakeRange(descRange.location, descRange.length)];
    }
    
    topicHighlight.tapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSLog(@"点击了topicText = %@, text = %@, range = %@, rect = %@", containerView,
              text.string, NSStringFromRange(range), NSStringFromCGRect(rect));
        NSString *str = [text.string substringWithRange:range];
        NSLog(@"---str = %@", str);
    };
    
    //notopic 的点击事件
    YYTextHighlight *noTopicHighlight = [YYTextHighlight new];
    for (NSValue *value in descRange) {
        NSLog(@"-----range = %@", NSStringFromRange(value.rangeValue));
        
        NSString *noTopicText = [attributedText.string substringWithRange: value.rangeValue];
        NSLog(@"noTopic = %@", noTopicText);
        
        //notopic 的点击事件
        [attributedText yy_setTextHighlight: noTopicHighlight range:NSMakeRange(value.rangeValue.location, value.rangeValue.length)];
    }
    
    __weak typeof(self) weakSelf = self;
    noTopicHighlight.tapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSLog(@"---点击了topicText = %@, text = %@, range = %@, rect = %@", containerView,
              text.string, NSStringFromRange(range), NSStringFromCGRect(rect));
        NSString *str = [text.string substringWithRange:range];
        NSLog(@"---str = %@", str);
        //点击 noTopic 文本
        [weakSelf noTopicTextTapAction];
    };
    
    return attributedText;
}

//点击 noTopic 文本
- (void)noTopicTextTapAction {
    self.hasClickedNameAndDescFirstText = !self.hasClickedNameAndDescFirstText;
    [self setTextLabelFrame:self.hasClickedNameAndDescFirstText];
    self.isHideUserInfoBtn.hidden = self.hasClickedNameAndDescFirstText;
    self.packUpBtn.hidden = !self.hasClickedNameAndDescFirstText;
    self.createTimeBtn.hidden = !self.hasClickedNameAndDescFirstText;
    self.shadeBtn.hidden = !self.hasClickedNameAndDescFirstText;
}

#pragma mark - 视频播放
- (void)vedioPlay {
    //获取VedioModel的数据
    VedioModel *vedioModel = self.mainModel.video;
    NSLog(@"--vedioModel = %@",vedioModel);
    //1、获取网络视频路径
    NSURL *url = [NSURL URLWithString:vedioModel.url];
    //2、创建媒体资源管理对象
    AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:url];
    
    self.player = [[AVPlayer alloc]initWithPlayerItem:playerItem];
    //3、创建显示视频的avplayerlayer,设置视频显示属性，并添加视频图层
    /*
     avlayervideogravityresizeaspectfill等比例铺满，宽或高有可能出屏幕
     avlayervideogravityresizeaspect 等比例 默认
     avlayervideogravityresize 完全适应宽高
    */
    AVPlayerLayer *avLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    avLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    NSLog(@"videoFrame = %@",NSStringFromCGRect(avLayer.videoRect));
    avLayer.frame = self.containerView.frame;
    [self.containerView.layer addSublayer:avLayer];
    
    //4、执行play方法，开始播放
   // [self.player play];
    
    //测试1：注册观察者，监测播放器属性
    //观察Status属性，可以在加载成功之后得到视频的长度
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    //测试2:刷新播放进度
    /**
     注意：使用addPeriodicTimeObserverForInterval必须持有返回对象，且在不需要播放器的时候移除此对象；
     否则将会导致undefined behavior
     @result
     An object conforming to the NSObject protocol.  You must retain this returned value as long as you want the time observer to be invoked by the player.
     Pass this object to -removeTimeObserver: to cancel time observation.
     Releasing the observer object without a call to -removeTimeObserver: will result in undefined behavior
     */
    __weak __typeof(self) weakSelf = self;
   self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //当前播放的时间
        NSTimeInterval currentTime = CMTimeGetSeconds(time);
        //视频的总时间
        NSTimeInterval totalTime = CMTimeGetSeconds(weakSelf.player.currentItem.duration);
        //设置滑块的当前进度
      // weakSelf.curProgress += BNTimderDuration;
      // [weakSelf.progressBar setValue:currentTime / totalTime animateWithDuration:1.0f time: 1];
       [ weakSelf.progressBar setValue:currentTime / totalTime];
       
       if (weakSelf.hasClickedPuaseBtn) {
           // YES，进度条高度4；NO，进度条高度为2
           weakSelf.progressBar.showLargeBar = YES;
           // YES，展示圆点；NO，隐藏圆点
           weakSelf.progressBar.showAnchorPoint = YES;
       } else {
           // YES，进度条高度4；NO，进度条高度为2
           weakSelf.progressBar.showLargeBar = NO;
           // YES，展示圆点；NO，隐藏圆点
           weakSelf.progressBar.showAnchorPoint = NO;
       }
       
       
      //  weakSelf.sliderView.value = currentTime/totalTime;
        //设置显示的时间：以00:00:00的格式
      //  weakSelf.currentPlayTimeLabel.text = [weakSelf formatTimeWithTimeInterVal:currentTime];
    }];
    //开始加载视频
   // self.sliderView.enabled = NO;
}

//


#pragma mark - private Methods

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        //获取playerItem的status属性最新的状态
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        switch (status) {
            case AVPlayerStatusReadyToPlay:{
               // CMTime duration = playerItem.duration; //获取视频长度
                //更新显示:视频总时长:
               // self.totalNeedPlayTimeLabel.text = [self formatTimeWithTimeInterVal:CMTimeGetSeconds(duration)];
                //开启滑块的滑动功能
               // self.sliderView.enabled = YES;
                //关闭加载Loading提示
               // [self showaAtivityInDicatorView:NO];
                //开始播放视频
              //  [self.player play];
//                self.progressBar.showLargeBar = NO;
//                self.progressBar.showAnchorPoint = NO;
                break;
            }
            case AVPlayerStatusFailed:{//视频加载失败，点击重新加载
                NSLog(@"视频加载失败，点击重新加载");
              //  [self showaAtivityInDicatorView:NO];//关闭Loading视图
              //  self.playerInfoButton.hidden = NO; //显示错误提示按钮，点击后重新加载视频
             //   [self.playerInfoButton setTitle:@"资源加载失败，点击继续尝试加载" forState: UIControlStateNormal];
                break;
            }
            case AVPlayerStatusUnknown:{
                NSLog(@"加载遇到未知问题:AVPlayerStatusUnknown");
                break;
            }
            default:
                break;
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        //获取视频缓冲进度数组，这些缓冲的数组可能不是连续的
        NSArray *loadedTimeRanges = playerItem.loadedTimeRanges;
        //获取最新的缓冲区间
        CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
        //缓冲区间的开始的时间
        NSTimeInterval loadStartSeconds = CMTimeGetSeconds(timeRange.start);
        //缓冲区间的时长
        NSTimeInterval loadDurationSeconds = CMTimeGetSeconds(timeRange.duration);
        //当前视频缓冲时间总长度
        NSTimeInterval currentLoadTotalTime = loadStartSeconds + loadDurationSeconds;
        //NSLog(@"开始缓冲:%f,缓冲时长:%f,总时间:%f", loadStartSeconds, loadDurationSeconds, currentLoadTotalTime);
        //更新显示：当前缓冲总时长
       // _currentLoadTimeLabel.text = [self formatTimeWithTimeInterVal:currentLoadTotalTime];
        //更新显示：视频的总时长
       // _totalNeedLoadTimeLabel.text = [self formatTimeWithTimeInterVal:CMTimeGetSeconds(self.player.currentItem.duration)];
        //更新显示：缓冲进度条的值
       // _progressView.progress = currentLoadTotalTime/CMTimeGetSeconds(self.player.currentItem.duration);
    }
}

//- (void)viewWillDisappear:(BOOL)animated{
//  //  [super viewWillDisappear:animated];
//    [self.player pause];
//    _player = nil;
//}

- (void)dealloc {
    if (self.player) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
       // [self.currentPlayerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [self.player removeTimeObserver:self.timeObserver];
        self.player = nil;
    }
}


#pragma mark - 获取 话题text
- (NSMutableArray<DescRange *> *)regexOfTopicTextWithDescText:(NSMutableString *)descText {
    NSMutableArray<DescRange *> *descRangeMarr = [NSMutableArray new];
    if (descText == nil || descText.length == 0) {
        return descRangeMarr;
    }
    //正则表达式
    //#(.*?)\\[话题]#
    NSString *pattern = @"#(\\S*?)\\[话题]#";
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray<NSTextCheckingResult *> *result = [regex matchesInString:descText options:0 range:NSMakeRange(0, descText.length)];
    
    if (result == nil || result.count <= 0) {
        return descRangeMarr;
    }
    
    NSString *topicSuffix = @"[话题]#";
    
    for (int i = 0; i < result.count; i++) {
        NSTextCheckingResult *res = result[i];
        NSRange topicRange = res.range;
        NSUInteger location = topicRange.location - topicSuffix.length * i;
        
        NSString *topic = [descText substringWithRange:NSMakeRange(location, topicRange.length)];
        NSLog(@"[%d]==============> 匹配到topic [%@]", i, topic);
        // 实际显示topic的内容长度 = topic总长度 - topicSuffix长度
        NSUInteger showTopicLength = topic.length - topicSuffix.length;
        // 截取出实际显示的topic内容
        NSString *showTopic = [topic substringToIndex: showTopicLength];
        
        NSLog(@"topic length: %ld, showTopic length: %ld", topic.length, showTopicLength);
        NSLog(@"topic: \"%@\", showTopic: \"%@\"", topic, showTopic);
        
        [descText replaceCharactersInRange:NSMakeRange(location, topicRange.length) withString:showTopic];
        
        // 除了第 0 个 topic，其他的第 n 个 topic 都需要减去 n * topicSuffix.length，才能得到实际显示的location
        
        DescRange *showTopicRange = [DescRange new];
        [showTopicRange setLocation:location];
        [showTopicRange setLength:showTopicLength];
        NSLog(@"正则匹配 range: {location=%ld, length=%ld}", topicRange.location, topicRange.length);
        NSLog(@"实际显示 range: {location=%ld, length=%ld}", showTopicRange.location, showTopicRange.length);
        
        [descRangeMarr addObject:showTopicRange];
        
        NSLog(@"_descText: \"%@\"", descText);
        
        printf("\n");
    }
    
    NSLog(@"[END]==============> 处理完所有topic <==============");
    return descRangeMarr;
}


#pragma mark - 将desc分成每一段
- (void) splitDesc {
    NSMutableArray<DescDetail *> *descMarr = [NSMutableArray new];
    _descRange = [NSMutableArray array];
    NSUInteger nextLocation = 0;
    for (int i = 0; i < _rangeMarr.count; i++) {
        DescRange *topicRange = _rangeMarr[i];
        
        if (topicRange.location == 0 && i == 0) {
            NSString *topicDesc = [_descText substringToIndex:topicRange.location + topicRange.length];
            nextLocation = topicRange.location + topicRange.length;
            NSLog(@"===> subDescStart: \"%@\", nextLocation: %ld", topicDesc, nextLocation);
            
            DescDetail *descDetail = [DescDetail new];
            [descDetail setDesc:topicDesc];
            [descDetail setIsTopic:true];
            [descMarr addObject:descDetail];
            continue;
        }
        
        NSString *topicBeforeDesc = [_descText substringWithRange:NSMakeRange(nextLocation, topicRange.location - nextLocation)];
        NSLog(@"i = %d, location = %ld, nextLocation = %ld,topicBeforeDesc = %@",i, topicRange.location, nextLocation, topicBeforeDesc);
        DescDetail *topicBeforeDescDetail = [DescDetail new];
        [topicBeforeDescDetail setDesc:topicBeforeDesc];
        [topicBeforeDescDetail setIsTopic:false];
        [descMarr addObject:topicBeforeDescDetail];
        NSValue *value1 = [NSValue valueWithRange:NSMakeRange(nextLocation, topicRange.location - nextLocation)];
        [_descRange addObject: value1];
        
        
        NSString *topicDesc = [_descText substringWithRange:NSMakeRange(topicRange.location, topicRange.length)];
        DescDetail *topicDescDetail = [DescDetail new];
        [topicDescDetail setDesc:topicDesc];
        [topicDescDetail setIsTopic:true];
        [descMarr addObject:topicDescDetail];
        
        nextLocation = topicRange.location + topicRange.length;
        
        NSLog(@"===> topicBeforeDesc: \"%@\"", topicBeforeDesc);
        NSLog(@"===> topicDesc1: \"%@\", nextLocation: %ld", topicDesc, nextLocation);
        
//        if (_desc.length == topicRange.location + topicRange.length) {
//            NSString *topicDesc = [_desc substringWithRange:NSMakeRange(topicRange.location, topicRange.length)];
//            NSLog(@"===> topicDesc2: \"%@\"", topicDesc);
//
//            DescDetail *descDetail = [DescDetail new];
//            [descDetail setDesc:topicDesc];
//            [descDetail setIsTopic:true];
//            [descMarr addObject:descDetail];
//            break;
//        }
        
        if (i == _rangeMarr.count - 1) {
            NSString *topicAfterDesc = [_descText substringFromIndex:nextLocation];
            NSLog(@"===> topicAfterDesc: \"%@\"", topicAfterDesc);

            DescDetail *topicAfterDescDetail = [DescDetail new];
            [topicAfterDescDetail setDesc:topicAfterDesc];
            [topicAfterDescDetail setIsTopic:false];
            [descMarr addObject:topicAfterDescDetail];
            [_descRange addObject: [NSValue valueWithRange:NSMakeRange(nextLocation, topicAfterDesc.length)]];
        }
    }
    
    NSLog(@"每一段 desc 的集合 descMarr: %@ - count = %ld", descMarr, descMarr.count);
    if (_rangeMarr.count == 0) {
        [_descRange addObject:[NSValue valueWithRange:NSMakeRange(0, _descText.length)]];
    }
    NSLog(@"_descRange = %@", _descRange);

//    _descStr = [NSMutableString string];
//    for (DescDetail *detail in descMarr) {
//        NSLog(@"detail = %@", detail);
//        [_descStr appendString: detail.desc];
//    }
//    _splitTextLabel.text = _descStr;
}

#pragma mark - 将desc分成每一段
- (NSMutableArray *) splitDesc:(NSString *)descText topicRanges:(NSMutableArray<DescRange *> *)topicRanges {
    NSMutableArray *descRange = [NSMutableArray array];
    
    if (topicRanges.count == 0) {
        [descRange addObject:[NSValue valueWithRange:NSMakeRange(0, descText.length)]];
    }
    
    NSUInteger nextLocation = 0;
    for (int i = 0; i < topicRanges.count; i++) {
        DescRange *topicRange = topicRanges[i];
        
        if (topicRange.location == 0 && i == 0) {
            nextLocation = topicRange.location + topicRange.length;
            continue;
        }
        
        NSValue *value = [NSValue valueWithRange:NSMakeRange(nextLocation, topicRange.location - nextLocation)];
        [descRange addObject: value];
        
        nextLocation = topicRange.location + topicRange.length;
        
        if (i == topicRanges.count - 1) {
            [descRange addObject: [NSValue valueWithRange:NSMakeRange(nextLocation, descText.length - nextLocation)]];
        }
    }
    return descRange;
}

#pragma mark - 获取自适应文本
- (CGSize)calculateSizeWithString:(NSString *)str textSize:(CGSize)textSize textFont:(UIFont *)textFont{
    return [str boundingRectWithSize:textSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: textFont} context:nil].size;
}


- (CGFloat )returnTextHeightWithStr:(NSString *)str withFont:(UIFont *)font WithWidth:(CGFloat)width WithLineSpacing:(CGFloat)lineSpacing  {
    UITextView* _textView = [[UITextView alloc]init];
    _textView.font = font;
    //设置行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = lineSpacing;
    NSMutableAttributedString *titleAttr = [[NSMutableAttributedString alloc] initWithString:str];
    [titleAttr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, titleAttr.length)];
    [titleAttr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, titleAttr.length)];
    _textView.attributedText = titleAttr;
    CGSize maxSize = CGSizeMake(width,CGFLOAT_MAX);
    CGSize newSize = [_textView sizeThatFits:maxSize];
    CGFloat height = ceilf(newSize.height);
    return height;
}

@end
